/* --================权限检查================-- */
const notificationBtn = document.getElementById('enable');

// 检查是否支持 Promise
const checkNotificationPromise = () => {
  try {
    Notification.requestPermission().then();
  } catch {
    return false;
  }
  return true;
}

// 检查通知权限
const askNotificationPermission = () => {
  // 访问权限的函数
  const handlePermission = (permission) => {
    console.log(permission); // granted 允许的；denied 拒绝的；
    if (permission === 'granted') {
      /* --================创建通知================-- */
      const n = new Notification('这是一段Notification文本');

      // 监听当页面重新显示时关闭通知
      document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'visible') {
          n.close();
        }
      })
    }
  }

  // 检查浏览器是否支持通知接口，并发起授权查询
  if (checkNotificationPromise()) {
    Notification.requestPermission()
      .then(premission => handlePermission(premission));
  } else {
    Notification.requestPermission(function (premission) {
      handlePermission(premission);
    });
  }
}

notificationBtn.addEventListener('click', askNotificationPermission);